package edu.gatech.oad.publicstaticdroidmain.taskmanager.ui;

import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class TaskArrayAdapter extends ArrayAdapter<Object> {
	private final Activity context;
	private final Object[] values;

	public TaskArrayAdapter(Activity context, Object[] values) {
		super(context, R.layout.row_layout, values);
		this.context = context;
		this.values = values;
	}

//	@Override
//	public View getView(int position, View convertView, ViewGroup parent) {
//		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		View rowView = inflater.inflate(R.layout.row_layout, parent, false);
//		TextView textView = (TextView) rowView.findViewById(R.id.label);
//		ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
//		textView.setText(values[position].toString());
//		// Change the icon for Windows and iPhone
//		boolean complete = ((Task)values[position]).isCompleted();
//		if (complete) {
//			imageView.setImageResource(android.R.drawable.ic_menu_delete);
//		} else {
//			imageView.setImageResource(android.R.drawable.ic_menu_add);
//		}
//
//		return rowView;
//	}
	
	static class ViewHolder {
		protected TextView text;
		protected CheckBox checkbox;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = context.getLayoutInflater();
			view = inflator.inflate(R.layout.row_layout, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.text = (TextView) view.findViewById(R.id.label);
			viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
			viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							Task element = (Task) viewHolder.checkbox.getTag();
							element.setSelected(buttonView.isChecked());

						}
					});
			view.setTag(viewHolder);
			viewHolder.checkbox.setTag(values[position]);
		} else {
			view = convertView;
			((ViewHolder) view.getTag()).checkbox.setTag(values[position]);
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		holder.text.setText(((Task) values[position]).getName());
		holder.checkbox.setChecked(((Task) values[position]).isSelected());
		return view;
	}
}
